 /**
 * 逻辑、功能相关描述:
 *
 * @author yandawei 编写日期：2008-10-16
 */
package com.ce.pms.common.web;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletResponse;

import org.jdom.Attribute;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.output.XMLOutputter;

import com.ce.pms.base.web.PmsBaseAction;
import com.ce.pms.common.model.SysrefcodeDO;
import com.ce.pms.common.service.IDataRightService;
import com.ce.pms.common.service.IDataRightService.DataRightType;
import com.ce.pms.common.vo.EmployeeRightVO;
import com.ce.pms.house.vo.BuildingVO;
import com.ce.pms.house.vo.CompanyVO;
import com.ce.pms.house.vo.ManageOrgVO;
import com.ce.pms.house.vo.PrecinctVO;
import com.ce.util.BlankUtil;
import com.sitechasia.webx.core.annotation.Out;
import com.sitechasia.webx.core.annotation.Read;
import com.sitechasia.webx.core.support.Page;

/**
 * 数据拦截权限分配
 *
 */
public class DataRightAction extends PmsBaseAction {

	private IDataRightService dataRightService;


	public void setDataRightService(IDataRightService dataRightService) {
		this.dataRightService = dataRightService;
	}

	/***
	 * 功能描述:  数据权限分配主界面<br>
	 * @return
	 * Create author:yandawei <br>
	 * Create on:2008-10-16  <br>
	 * Edit author:  <br>
	 * Edit on:    <br>
	 * Why:     <br>
	 */
	public String initDataRightMain(){
		return "initDataRightMain";
	}

	/***
	 * 功能描述:  初始化权限查询方法<br>
	 * @return
	 * Create author:yandawei <br>
	 * Create on:2008-10-16  <br>
	 * Edit author:  <br>
	 * Edit on:    <br>
	 * Why:     <br>
	 */
	public String initEmployeeQueryList(){
		setAttribute("totalRows",new Integer(0));
		return "employeeList";
	}


	/***
	 * 功能描述:  数据权限查询<br>
	 * @param employee 查询条件
	 * @param pageNO
	 * @param pageSize
	 * @return
	 * Create author:yandawei <br>
	 * Create on:2008-10-16  <br>
	 * Edit author:  <br>
	 * Edit on:    <br>
	 * Why:     <br>
	 */
	public String queryEmployeeList(
			@Read EmployeeRightVO employee,
			@Read(key = "ec_p", defaultValue = "1") Integer pageNO,
			@Read(key = "ec_crd",defaultValue = "15")Integer pageSize){
		Page page = dataRightService.queryEmployeeDataRight(employee, pageNO, pageSize);
		setAttribute("EmployeeList", page.getResult());
		setAttribute("totalRows",Integer.valueOf(String.valueOf(page.getTotalCount())));
		return "employeeList";
	}


	/***
	 * 功能描述:  数据权限分配主界面<br>
	 * @param userId
	 * @return
	 * Create author:yandawei <br>
	 * Create on:2008-10-16  <br>
	 * Edit author:  <br>
	 * Edit on:    <br>
	 * Why:     <br>
	 */
	public String initEmployeeRightMain(
			@Read(key="userId")@Out(key="userId") Long userId){

		if(dataRightService.hasUserDataRight(userId)){
			if(dataRightService.isPrecinctRight(userId))
				setAttribute("rightType", SysrefcodeDO.COMMON_DATA_RIGHT_PRECINCT);
			else
				setAttribute("rightType", SysrefcodeDO.COMMON_DATA_RIGHT_BUILDING);
		}else{
			setAttribute("rightType", "-1");//未分配权限的状态
		}
		return "dataRightDistribution";
	}

	/***
	 * 功能描述:  根据用户选择的权限类型加载权限树(界面选择时调用)<br>
	 * @param rightType
	 * @param userId
	 * @return
	 * Create author:yandawei <br>
	 * Create on:2008-10-17  <br>
	 * Edit author:  <br>
	 * Edit on:    <br>
	 * Why:     <br>
	 */
	public String getEmployeeRight(
			@Read(key="rightType")String rightType,
			@Read(key="userId")@Out(key="userId")Long userId){
		if("-1".equals(rightType)){
			rightType =SysrefcodeDO.COMMON_DATA_RIGHT_BUILDING;
		}
		setAttribute("rightType", rightType);
		return "dataRightTree";
	}


	/***
	 * 功能描述: 初始化权限树 <br>
	 * @param rightType
	 * @param userId
	 * Create author:yandawei <br>
	 * Create on:2008-10-17  <br>
	 * Edit author:  <br>
	 * Edit on:    <br>
	 * Why:     <br>
	 */
	public void getRightTreeData(
			@Read(key="rightType")String rightType,
			@Read(key="userId")Long userId){
		try {
			    Map<CompanyVO, Map<ManageOrgVO, Map<PrecinctVO, List<BuildingVO>>>> superMap = dataRightService.getManageTree();
			    HttpServletResponse response = getResponse();
				response.setContentType("text/xml;charset=UTF-8");
				Element rootElement =  generationRootNode();
				Document doc = new Document(rootElement);
				//用户以分配的权限
				Long[] rightIds = dataRightService.getUserDataRight(userId);
				boolean hasPrecinctRight = dataRightService.isPrecinctRight(userId);
				List<Long> idlist  = BlankUtil.isBlank(rightIds) ? new ArrayList<Long>() :Arrays.asList(rightIds);
				if(!BlankUtil.isBlank(superMap)){
					Set set1 = superMap.entrySet();
					for(Iterator it1 = set1.iterator() ; it1.hasNext();){
						Entry<CompanyVO, Map<ManageOrgVO, Map<PrecinctVO, List<BuildingVO>>>> entry = (Entry<CompanyVO, Map<ManageOrgVO, Map<PrecinctVO, List<BuildingVO>>>>) it1.next();
						CompanyVO com1 = entry.getKey();
						Element item = generationNode(com1.getKeyword(), com1.getName(),"company_");
						rootElement.addContent(item);
						Set set2 = entry.getValue().entrySet();
						//设置节点有子节点
						if(set2.size()>0){
							item.setAttribute("child","1");
						}
						for(Iterator it2 = set2.iterator() ; it2.hasNext();){
							Entry<ManageOrgVO,Map<PrecinctVO, List<BuildingVO>>> entry2 = (Entry<ManageOrgVO, Map<PrecinctVO, List<BuildingVO>>>) it2.next();
							ManageOrgVO man2 = entry2.getKey();
							Element item2 = generationNode(man2.getKeyword(), man2.getName(),"manageOrg_");
							item.addContent(item2);
							Set set3 = entry2.getValue().entrySet();
							if(set3.size()>0){
								item2.setAttribute("child","1");
							}
							for(Iterator it3 = set3.iterator() ; it3.hasNext();){
								Entry<PrecinctVO , List<BuildingVO>> entry3 =  (Entry<PrecinctVO, List<BuildingVO>>) it3.next();
								PrecinctVO pre3 = entry3.getKey();
								Element item3 = generationNode(pre3.getKeyword(), pre3.getName(),"precinct_");
								//设置节点为选中状态
								if(hasPrecinctRight && idlist.contains(pre3.getKeyword())){
									item3.setAttribute("checked", "1");
								}
								item2.addContent(item3);
								List<BuildingVO> buildLists = entry3.getValue();
								if(buildLists.size()>0 && SysrefcodeDO.COMMON_DATA_RIGHT_BUILDING.equals(rightType)){
									item3.setAttribute("child","1");
									for (BuildingVO buildingVO : buildLists) {
										Element itemBuiding = generationNode(buildingVO.getKeyword(), buildingVO.getName(),"building_");
										itemBuiding.setAttribute("child","0");
										if(idlist.contains(buildingVO.getKeyword())){
											itemBuiding.setAttribute("checked","1");
										}
										item3.addContent(itemBuiding);
									}
								}
							}
						}
					}
				}

				XMLOutputter XMLOut = new XMLOutputter();
				PrintWriter out = response.getWriter();
				XMLOut.output(doc, out);
				out.flush();

//				XMLOutputter outputter = new XMLOutputter();
//				FileWriter writer = new FileWriter("c:\\myFile.xml");
//				outputter.output(doc, writer);
//				writer.close();

			   } catch(IOException ioe) {

			   }
	}

	/***
	 * 功能描述:  修改/新增用户数据权限<br>
	 * @param rightType
	 * @param userId
	 * @param idstr
	 * Create author:yandawei <br>
	 * Create on:2008-10-16  <br>
	 * Edit author:  <br>
	 * Edit on:    <br>
	 * Why:     <br>
	 */
	public void editDataRight(
			@Read(key="userId")Long userId,
			@Read(key="rightType")String rightType,
			@Read(key="idstr")String idstr){
		Long[] ids = null;
		if(!BlankUtil.isBlank(idstr)){
			String[] strs = idstr.split(",");
			ids = new Long[strs.length];
			for(int i = 0 ; i < strs.length; i++){
				ids[i] = Long.parseLong(strs[i]);
			}
		}
		Long optUser = getUserId();
		dataRightService.saveDataRight(optUser,userId, wrapString2Enum(rightType), ids);
		this.renderText("true");
	}

	/***
	 * 功能描述:  将字符品权限类型转换为枚举<br>
	 * @param rightType
	 * @return
	 * Create author:yandawei <br>
	 * Create on:2008-10-23  <br>
	 * Edit author:  <br>
	 * Edit on:    <br>
	 * Why:     <br>
	 */
	private DataRightType wrapString2Enum(String rightType){
		if(SysrefcodeDO.COMMON_DATA_RIGHT_PRECINCT.equals(rightType))
			return DataRightType.PRECINCT;
		else
			return DataRightType.BUILDING;
	}

	/***
	 * 功能描述: 生成树根节点 <br>
	 * @return
	 * Create author:yandawei <br>
	 * Create on:2008-10-23  <br>
	 * Edit author:  <br>
	 * Edit on:    <br>
	 * Why:     <br>
	 */
	private Element generationRootNode() {
		Element rootElement = new Element("tree");
		Attribute rootAttri = new Attribute("id", "0");
		rootElement.setAttribute(rootAttri);
		rootElement.setAttribute("select", "true");
		rootElement.setAttribute("tooltip", "根接点");
		return rootElement;
	}


	/***
	 * 功能描述:  生成树节点<br>
	 * @param id
	 * @param text
	 * @return
	 * Create author:yandawei <br>
	 * Create on:2008-10-23  <br>
	 * Edit author:  <br>
	 * Edit on:    <br>
	 * Why:     <br>
	 */
	private Element generationNode(Long id,String text,String preFix) {
		Element item = new Element("item");
		item.setAttribute("id",String.valueOf(preFix+id));
		item.setAttribute("text", text);
		item.setAttribute("im1", "root.gif");
		item.setAttribute("im2", "root.gif");
		return item;
	}


}
